package no.ntnu.fp.handlers;

import java.io.IOException;

import no.ntnu.fp.connection.ReceiveWorker;
import no.ntnu.fp.handler.Handler;
import no.ntnu.fp.handlers.exceptions.NetworkException;
import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.impl.AddMeetingMessage;
import no.ntnu.fp.messages.impl.MeetingAddedMessage;
import no.ntnu.fp.messages.impl.NoticeAddedOrUpdatedMessage;
import no.ntnu.fp.model.Employee;
import no.ntnu.fp.model.Meeting;
import no.ntnu.fp.model.Notice;
import no.ntnu.fp.model.Notice.NoticeType;
import no.ntnu.fp.net.co.Connection;
import no.ntnu.fp.server.MainConnection;
import no.ntnu.fp.services.MeetingService;
import no.ntnu.fp.services.NoticeService;
import no.ntnu.fp.utils.Participant;

public class AddMeetingHandler implements Handler {

	private final MeetingService meetingService;
	private final NoticeService noticeService;
	
	public AddMeetingHandler(MeetingService meetingService,
							 NoticeService noticeService) {
		this.meetingService = meetingService;
		this.noticeService = noticeService;
	}

	@Override
	public void handleMessage(Message message) {
		AddMeetingMessage addMeetingMessage = (AddMeetingMessage) message;
		
		Meeting meeting = meetingService.addMeeting(addMeetingMessage.getMeeting());
		
		noticeService.notifyParticipants(meeting, NoticeType.NewMeeting, 
														meeting.getEmployee());
		
		MeetingAddedMessage reply = new MeetingAddedMessage(meeting);
		
		Connection connection = ReceiveWorker.getThreadLocalConnection();
		try {
			connection.send(reply.toString());
		} catch (IOException e) {
			throw new NetworkException("Unable to send message adding ack " +
									   "for message " + message, e);
		}
	}

}
